/*
 * @Author: HeAo
 * @Date: 2021-11-04 15:11:16
 * @LastEditTime: 2021-11-04 16:39:33
 * @LastEditors: HeAo
 * @Description:
 * @FilePath: \web2103-2105\web2105\4-1-Nodejs\day05\briup-sc\routes\student.js
 * 别乱动！
 */
const express = require('express');
const router = express.Router();
const Response = require('../utils/Response');
// 导入数据库连接池
const pool = require('../utils/Connection')

router.get('/findAll', (req, res) => {
  // 2.通过连接池获取连接对象
  pool.getConnection((err, connection) => {
    if (err) throw err

    // 3.查询
    const sql = `select * from tab_student`
    connection.query(sql, (error, result) => {
      if (error) throw error
      res.send(new Response(20000, '查询成功', result))
      // 4.释放连接
      connection.release();
    })
  })
})

router.post('/saveOrUpdate', (req, res) => {
  let stu = req.body
  let sql = `insert into tab_student(name, gender) values('${stu.name}','${stu.gender}')`
  // 判断前端传递的请求体数据中是否包含ID字段
  if (stu.id) {
    sql = `update tab_student set name='${stu.name}',gender='${stu.gender}' where id = ${stu.id}`
  }
  pool.getConnection((err, connection) => {
    if (err) throw err

    connection.query(sql, (error, result) => {
      if (error) throw error

      res.send(new Response(20000, '保存成功', null))
      connection.release()
    })
  })
})

router.delete('/deleteById', (req, res) => {
  const id = req.query.id
  const sql = `delete from tab_student where id = ${id}`
  pool.getConnection((err, connection) => {
    if (err) throw err
    connection.query(sql, (error, result) => {
      if (error) throw error

      console.log(result);
      res.send(new Response(20000, '删除成功', null))
      connection.release()
    })
  })
})

module.exports = router

